#include "boost/locale/encoding.hpp"
#include "boost/locale.hpp"
#include "BSException/BSException.h"
#include "UTF8.h"
#include "GB2312.h"

#define GB2312_ENCODE_STRING "GB2312"

#define UTF8_ENCODE_STRING "UTF8"

using namespace SystemTool;
using namespace SystemTool::Encoding;

// Get string from unicode
std::string GB2312::GetString(const std::wstring strUnicodeData, EncodeType eEncodeType)
{
	if (strUnicodeData.empty())
	{
		return "";
	}

	std::string strFinalData = "";

	std::string strUtf8Data = "";

	try
	{
		if (eEncodeType == ENCODE_GBK || eEncodeType == ENCODE_GB2312)
		{
			strUtf8Data = UTF8::GetString(strUnicodeData, eEncodeType);
		}
		else if (eEncodeType == ENCODE_UTF8)
		{
			strUtf8Data = boost::locale::conv::utf_to_utf<char>(strUnicodeData);
		}

		strFinalData = boost::locale::conv::from_utf(strUtf8Data, GB2312_ENCODE_STRING);
	}
	catch (std::bad_cast & e)
	{
		throw BSException() << e.what();
	}

	return strFinalData;
}

// Get string from utf8
std::string GB2312::GetString(const std::string strData, EncodeType eEncodeType)
{
	if (strData.empty())
	{
		return "";
	}

	try
	{
		if (eEncodeType == ENCODE_UTF8)
		{
			return boost::locale::conv::between(strData, GB2312_ENCODE_STRING, UTF8_ENCODE_STRING);
		}
		else if (eEncodeType == ENCODE_GBK || eEncodeType == ENCODE_GB2312)
		{
			return strData;
		}
	}
	catch (std::bad_cast & e)
	{
		throw BSException() << e.what();
	}
	
	return "";
}
